﻿using AutoMapper;
using MediatR;
using RBAC.Domain;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.User;

namespace RBAC.Write.Api.Application.Handler.User
{
    public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, APIResult<int>>
    {
        private readonly IBaseRepository<UserModel> userRepository;
        private readonly ILogger<UpdateUserHandler> logger;
        private readonly IMapper mapper;
        private readonly IBaseRepository<UserRoleModel> userRoleRepository;

        public UpdateUserHandler(IBaseRepository<UserModel> userRepository, ILogger<UpdateUserHandler> logger, IMapper mapper, IBaseRepository<UserRoleModel> userRoleRepository)
        {
            this.userRepository = userRepository;
            this.logger = logger;
            this.mapper = mapper;
            this.userRoleRepository = userRoleRepository;
        }
        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var user = userRepository.GetALL().FirstOrDefault(x => x.Id == request.Id);
            var userroles = userRoleRepository.GetALL().Where(x => x.UserId == request.Id).ToList();
            foreach (var item in userroles)
            {
                item.IsDeleted = true;
                userRoleRepository.Update(item);
            }
            var data = mapper.Map(request, user);

            var r = userRepository.Update(data);

            foreach (var item in request.RoleId)
            {
                var userrole = new UserRoleModel()
                {
                    UserId = user.Id,
                    RoleId = item,
                };
                var r2 = userRoleRepository.Update(userrole);
            }
            if (r > 0)
            {
                res.Data = r;
                res.Code = APIEnums.Success;
                res.Msg = "修改成功";
                return Task.FromResult(res);
            }
            else
            {
                res.Code = APIEnums.Fail;
                res.Msg = "修改失败";
                return Task.FromResult(res);
            }
        }
    }
}
